# Maintainer: Johannes Schindelin <johannes.schindelin@gmx.de>

_realname=busybox
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-${_realname}-pdb")
_ver_base=1.28.0pre
pkgver=1.28.0pre.16550.0b3cdd76c
pkgrel=1
pkgdesc="Windows port of BusyBox (mingw-w64)"
arch=('any')
url="https://github.com/git-for-windows/busybox-w32"
makedepends=("${MINGW_PACKAGE_PREFIX}-cv2pdb")
license=('GPL2')

options=('!strip')
source=("git+https://github.com/git-for-windows/busybox-w32")
sha256sums=('SKIP')

pkgver() {
  cd ${srcdir}/${_realname}-w32
  printf "%s.%s.%s" "$_ver_base" \
    "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}

prepare() {
  cd ${srcdir}/${_realname}-w32

  rm -f .config

  case "$CARCH" in
  i686)
    make mingw32_defconfig
    ;;
  x86_64)
    make mingw64_defconfig
    ;;
  *)
    echo "Could not prepare for architecture $CARCH" >&2
    exit 1
    ;;
  esac
}

build() {
  cd ${srcdir}/${_realname}-w32

  # Let BusyBox decide whether it wants to use MINGW's ANSI emulation or not
  F="${CPPFLAGS% -D__USE_MINGW_ANSI_STDIO=*}"
  test "a$F" = "a$CPPFLAGS" ||
  CPPFLAGS="$F${CPPFLAGS##* -D__USE_MINGW_ANSI_STDIO=*}"

  make clean
  make busybox_unstripped.exe
  cv2pdb busybox_unstripped.exe busybox.exe busybox.pdb
}

package() {
  cd ${srcdir}/${_realname}-w32

  test pdb != "$1" || {
    install -d -m 755 "${pkgdir}${MINGW_PREFIX}/bin"
    install -m 755 busybox.pdb "${pkgdir}${MINGW_PREFIX}/bin"
    return
  }

  # install into $MINGW_PREFIX/bin/
  ! grep -q '\$prefix/bin' applets/install.sh ||
  sed -i "s|\\(\\\$prefix\\)\\(/bin\\)|\\1$MINGW_PREFIX\\2|g" \
    applets/install.sh

  # install hardlinked applets into $MINGW_PREFIX/libexec/busybox/
  make busybox.links
  sed -i "s|.*/|$MINGW_PREFIX/libexec/busybox/|" busybox.links

  install -m0755 -d "${pkgdir}$MINGW_PREFIX/libexec/busybox"
  ./applets/install.sh "${pkgdir}" --hardlinks
}

package_mingw-w64-i686-busybox() {
  package
}

package_mingw-w64-x86_64-busybox() {
  package
}

package_mingw-w64-i686-busybox-pdb() {
  package pdb
}

package_mingw-w64-x86_64-busybox-pdb() {
  package pdb
}
